package com.ssm.modules.controller;

import com.ssm.common.bean.VResponse;
import com.ssm.modules.entity.User;
import com.ssm.modules.service.IUserService;
import com.ssm.modules.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;

/**
 * @email:
 * @author:
 * @date: 2018/12/18
 * @time: 17:20
 * 登录Controller
 */
@Controller
public class LoginController {

    @Autowired
    private IUserService userService;


    @ResponseBody
    @RequestMapping(value="/onlineCount")
    public VResponse<Object> onlineNum(HttpServletRequest request,
                                       HttpServletResponse response) throws IOException{
        return VResponse.success("在线人数: "+ (Integer) request.getServletContext().getAttribute("onlineCount"));
    }

    /**
     * 跳转登录页面
     * @param request
     * @return
     */
    @RequestMapping(value="/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request,
                        Map<String, Object> map) {
        User user = (User) request.getSession().getAttribute("user");
        if(user != null) {
            return "redirect:/index";
        }
        map.put("onlineCount", (Integer) request.getServletContext().getAttribute("onlineCount"));
        return "login";
    }

    /**
     * 登录操作
     * @param userName
     * @param password
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/login", method = RequestMethod.POST)
    public VResponse<User> login(@RequestParam("userName") String userName,
                                 @RequestParam("password") String password,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {

        try {
            // 获取session
            HttpSession session = request.getSession();
            // 查询该session是否已经登录
            User user = (User) session.getAttribute("user");
            if(user != null) {
                return VResponse.success("你已经登录");
            }

            user = userService.findByUserName(userName);
            if(user == null || ! SecurityUtils.validatePassword(password, user.getPassword())) {
                return VResponse.error(0, "用户名或密码错误");
            }

            // 将用户存入session
            session.setAttribute("user", user);


            /**
             *  如果该用户已经登录，退出上次登录的用户
             */

            // 获取ServletContext
            ServletContext context = session.getServletContext();
            //  获取有效sessionSet集合
            HashSet<HttpSession> sessionSet = (HashSet<HttpSession>) context.getAttribute("sessionSet");
            //  循环遍历
            for(HttpSession s: sessionSet) {
                User sUser = (User) s.getAttribute("user");
                if(sUser != null) {
                    String name = sUser.getUserName();
                    if(session != null && s != null && name != null &&
                            session != s && user.getUserName().equals(name)) {
                        // 从集合移除会话
                        sessionSet.remove(s);
                        // 销毁会话，触发监听器sessionDestroyed方法
                        s.invalidate();
                        break;
                    }
                }
            }



            user.setPassword("");
            return VResponse.success("登录成功", user);
        } catch (Exception e) {
            e.printStackTrace();
            return VResponse.error(0, "用户名或密码错误");
        }
    }

    /**
     * 注销操作，不是销毁session，因此不会触发sessionDestroyed方法，需要我们自己实现移除session操作
     * @param session
     * @return
     */
    @RequestMapping("/outLogin")
    public void outLogin(HttpSession session,
                         HttpServletResponse response) throws IOException {
        ServletContext context = session.getServletContext();
        // 在线人数减1
        int lineCount = (Integer) context.getAttribute("onlineCount");
        context.setAttribute("onlineCount", lineCount - 1);
        HashSet<HttpSession> sessionSet = (HashSet<HttpSession>) context.getAttribute("sessionSet");
        if(sessionSet != null){
            // 移除session
            sessionSet.remove(session);
            // 销毁session
            session.invalidate();
        }

        // 跳转到登录页面
        response.sendRedirect("/login");
    }


}
